//
//  WPShareToCommonCaseVC.m
//  wobingwoyi
//
//  Created by WGP on 2016/11/25.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPShareToCommonCaseVC.h"
#import "WPNewEditeSpecificCasesVC.h"
#import "WPMRModel.h"
#import "WPPerfectCommonCaseVC.h"

@interface WPShareToCommonCaseVC ()

@property(nonatomic,strong)UIView *navBarView;
@property(nonatomic,strong)UIImageView *descpImageView;
@property(nonatomic,strong)UILabel *descpLabel;
@property(nonatomic,strong)UIButton *shareBtn;

@property(nonatomic,strong)UIButton *checkInstanceBtn;
@property(nonatomic,strong)UIButton *performCaseBtn;
@property(nonatomic,assign)BOOL isShow;
@property(nonatomic,strong)UILabel *tipLabel;

@end

@implementation WPShareToCommonCaseVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBar.hidden = YES;
    self.view.backgroundColor = GlobalBgColor;
    
    [self setupUI];
}

-(void)setupUI
{
    [self navBarView];
    [self descpImageView];
    [self descpLabel];
    [self shareBtn];
    
    [self checkInstanceBtn];
    [self performCaseBtn];
    
    [self tipLabel];
}

-(UIView *)navBarView
{
    if (_navBarView == nil)
    {
        UIView *stateView = [UIView new];
        stateView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:stateView];
        
        [stateView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(self.view);
            make.height.mas_equalTo(20);
        }];
        
        _navBarView = [UIView new];
        _navBarView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_navBarView];
        
        [_navBarView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.view);
            make.top.equalTo(stateView).offset(20);
            make.height.mas_equalTo(44);
        }];
        
        UILabel *titleLabel = [UILabel new];
        titleLabel.text = self.index == 0 ? @"共享到普通病例" : @"共享到精华病例";
        titleLabel.font = [UIFont systemFontOfSize:18];
        titleLabel.textColor = GLobalFontColor;
        [_navBarView addSubview:titleLabel];
        
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(_navBarView);
        }];
        
        UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [backBtn setTitle:@"取消" forState:UIControlStateNormal];
        backBtn.titleLabel.font = [UIFont systemFontOfSize:15   ];
        [backBtn setTitleColor:GLobalFontColor forState:UIControlStateNormal];
        [backBtn addTarget:self action:@selector(backBtnDidClick) forControlEvents:UIControlEventTouchUpInside];
        [_navBarView addSubview:backBtn];
        
        [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_navBarView);
            make.left.equalTo(self.navBarView).offset(15);
        }];
        
        UIImageView *lineView = [UIImageView lineImageView];
        [_navBarView addSubview:lineView];
        
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(_navBarView);
            make.height.mas_equalTo(0.5);
        }];
    }
    return _navBarView;
}

-(UIImageView *)descpImageView
{
    if (_descpImageView == nil)
    {
        UIImage *image = [UIImage imageNamed:@"shareToCommonCase"];
        _descpImageView = [[UIImageView alloc] initWithImage:image];
        [self.view addSubview:_descpImageView];
        
        CGFloat left = 54 * SCREEN_WIDTH/375.0;
        CGFloat imageWidth = SCREEN_WIDTH - 2*left;
        CGFloat imageHeight = imageWidth*image.size.height/image.size.width;
        
        [_descpImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.top.equalTo(self.navBarView.mas_bottom).offset(30*K_SCALE_ELSE_TABBAR);
            make.width.mas_equalTo(imageWidth);
            make.height.mas_equalTo(imageHeight);
            
        }];
    }
    return _descpImageView;
}

-(UILabel *)descpLabel
{
    if (_descpLabel == nil)
    {
        _descpLabel = [UILabel new];
        _descpLabel.textColor = GLobalFontColor;
        _descpLabel.numberOfLines = 0;
        
        NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
        paraStyle.lineSpacing = UILABEL_LINE_SPACE; //设置行间距
        paraStyle.alignment = NSTextAlignmentCenter;
        NSDictionary *dic = @{
                              NSFontAttributeName:[UIFont systemFontOfSize:13], NSParagraphStyleAttributeName:paraStyle
                              };
        NSAttributedString *attributeStr = nil;
        
        if (self.index)
        {
            attributeStr = [[NSAttributedString alloc] initWithString:@"分享为精华病例需要填写的数据请参考\n\"查看示例\",病例共享汇聚医学力量" attributes:dic];
        }
        else
        {
            attributeStr = [[NSAttributedString alloc] initWithString:@"分享为普通病例需要填写的数据请参考\n\"查看示例\",让您的病例\"云\"起来" attributes:dic];
        }
        
        _descpLabel.attributedText = attributeStr;
        [self.view addSubview:_descpLabel];
        
        [_descpLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.top.equalTo(self.descpImageView.mas_bottom).offset(34*K_SCALE_ELSE_TABBAR);
        }];
    }
    return _descpLabel;
}

-(UIButton *)shareBtn
{
    if (_shareBtn == nil)
    {
        _shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_shareBtn setTitle:@"完成共享" forState:UIControlStateNormal];
        _shareBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_shareBtn setTitleColor:GLobalFontColor forState:UIControlStateNormal];
        [_shareBtn setBackgroundImage:[UIImage imageNamed:@"shareDoneBtn_normal"] forState:UIControlStateNormal];
        [_shareBtn setBackgroundImage:[UIImage imageNamed:@"shareDoneBtn_highlight"] forState:UIControlStateHighlighted];
        [_shareBtn addTarget:self action:@selector(shareDoneBtnDidClick) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_shareBtn];
        
        [_shareBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.view);
            make.height.mas_equalTo(50);
        }];
    }
    return _shareBtn;
}

-(UIButton *)checkInstanceBtn
{
    if (_checkInstanceBtn == nil)
    {
        _checkInstanceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_checkInstanceBtn setBackgroundImage:[UIImage imageNamed:@"commonBtn_normal"] forState:UIControlStateNormal];
        [_checkInstanceBtn setBackgroundImage:[UIImage imageNamed:@"commonBtn_highlight"] forState:UIControlStateHighlighted];
        [_checkInstanceBtn setImage:[UIImage imageNamed:@"check_icon"] forState:UIControlStateNormal];
        [_checkInstanceBtn setImage:[UIImage imageNamed:@"check_icon"] forState:UIControlStateHighlighted];
        [_checkInstanceBtn setTitle:@"  查看示例" forState:UIControlStateNormal];
        [_checkInstanceBtn setTitleColor:GLobalFontColor forState:UIControlStateNormal];
        [_checkInstanceBtn addTarget:self action:@selector(checkOrPerformBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
        _checkInstanceBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [self.view addSubview:_checkInstanceBtn];
        
        [_checkInstanceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.top.equalTo(self.descpLabel.mas_bottom).offset(40*K_SCALE_ELSE_TABBAR);
            make.height.mas_equalTo(44);
        }];
    }
    return _checkInstanceBtn;
}

-(UIButton *)performCaseBtn
{
    if (_performCaseBtn == nil)
    {
        _performCaseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_performCaseBtn setBackgroundImage:[UIImage imageNamed:@"commonBtn_normal"] forState:UIControlStateNormal];
        [_performCaseBtn setBackgroundImage:[UIImage imageNamed:@"commonBtn_highlight"] forState:UIControlStateHighlighted];
        [_performCaseBtn setImage:[UIImage imageNamed:@"performCase_icon"] forState:UIControlStateNormal];
        [_performCaseBtn setImage:[UIImage imageNamed:@"performCase_icon"] forState:UIControlStateHighlighted];
        [_performCaseBtn setTitle:@"  完善病例" forState:UIControlStateNormal];
        [_performCaseBtn setTitleColor:GLobalFontColor forState:UIControlStateNormal];
        [_performCaseBtn addTarget:self action:@selector(checkOrPerformBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
        _performCaseBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [self.view addSubview:_performCaseBtn];
        
        [_performCaseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.top.equalTo(self.checkInstanceBtn.mas_bottom).offset(15*K_SCALE_ELSE_TABBAR);
            make.height.mas_equalTo(44);
        }];
    }
    return _performCaseBtn;
}

#pragma mark - 按钮响应事件

-(void)checkOrPerformBtnDidClick:(UIButton *)btn
{
    if (btn == self.checkInstanceBtn)
    {
        [self showWithStatus:@"正在加载"];
        
        NSString *url = @"record/findRecordById.do";
        [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:@{@"id":@(1)} progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            [self dismiss];
            if([responseObject[@"result"] isEqualToString:@"success"])
            {
                WPMRModel *model = [WPMRModel yy_modelWithDictionary:responseObject[@"detail"]];
                
                if(self.index)
                {
                    //查看精华完成病例
                    //查看普通完成病例
                    WPPerfectCommonCaseVC *rirVC = [WPPerfectCommonCaseVC new];
                    rirVC.isExample = YES;
                    rirVC.isChargeExample = YES;
                    rirVC.model = model;
                    [self.navigationController pushViewController:rirVC animated:YES];
                }
                else
                {
                    //查看普通完成病例
                    WPPerfectCommonCaseVC *rirVC = [WPPerfectCommonCaseVC new];
                    rirVC.isExample = YES;
                    rirVC.model = model;
                    [self.navigationController pushViewController:rirVC animated:YES];
                }
            }
            else
            {
                //            考虑到账号过期的情况
                if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
                {
                    //                账号过期
                    [self illegalLoginWithSuccessBlock:^{
                        
                        //点击确定
                        WPMineLoginVC *vc = [WPMineLoginVC new];
                        [self presentViewController:[[UINavigationController alloc] initWithRootViewController:vc] animated:YES completion:nil];
                    }];
                }
                else
                {
                    [self showErrorInfoWithStatus:responseObject[@"detail"]];
                }
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            [self dismiss];
            [self showErrorInfoWithStatus:@"网络错误"];
        }];
        
    }
    else
    {
        WPNewEditeSpecificCasesVC *vc = [WPNewEditeSpecificCasesVC new];
        //    vc.delegate = self;
        vc.isBack = YES;
        vc.model = self.model;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

-(void)shareDoneBtnDidClick
{
    if (self.index)
    {
        //共享到精华病例
        [self shareSpecialRecord];
    }
    else
    {
        if (self.isShow)
        {
            return ;
        }
        else
        {
            //分享到普通病例
            [self shareRecord];
        }
    }
}

//共享到普通病例
-(void)shareRecord
{
    NSString *url = @"record/shareRecord.do";
    
    NSDictionary *dict = @{@"recordId":@(self.model.id)};
    
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        if([responseObject[@"result"] isEqualToString:@"success"])
        {
            self.model.verified = YES;
            [self showSharedNormalRecordResultWith:YES tipStr:@"您的病例已共享成功"];
        }
        else
        {
            [self showSharedNormalRecordResultWith:NO tipStr:@"完善您的病例后才能分享"];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self showErrorInfoWithStatus:@"网络错误"];
    }];
}

//共享到精华病例
-(void)shareSpecialRecord
{
    NSString *url = @"record/shareSpecialRecord.do";
    NSDictionary *dict = @{@"recordId":@(self.model.id)};
    
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       
        if([responseObject[@"result"] isEqualToString:@"success"])
        {
            [self showSharedSpecialRecordResult];
        }
        else
        {
            if ([responseObject[@"detail"] isEqualToString:@"recordIncomplete"])
            {
                //病例不完整
                [self showSharedNormalRecordResultWith:NO tipStr:@"完善您的病例后才能分享"];
            }
            else if([responseObject[@"detail"] isEqualToString:@"duplicatApply"])
            {
                //重复申请
                [self showSharedNormalRecordResultWith:NO tipStr:@"正在审核中"];
            }
            else
            {
                [self showErrorInfoWithStatus:@"未知错误"];
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self showErrorInfoWithStatus:@"网络错误"];
    }];
}


/**
 共享到普通病例的结果提示

 @param isSuccess 共享是否成功
 @param tipStr 提示的内容
 */
-(void)showSharedNormalRecordResultWith:(BOOL)isSuccess tipStr:(NSString *)tipStr
{
    self.isShow = YES;
    
    UILabel *tipLabel = [UILabel new];
    tipLabel.textColor = [UIColor whiteColor];
    tipLabel.backgroundColor = RGB_SAME(77);
    tipLabel.text = tipStr;
    tipLabel.font = [UIFont systemFontOfSize:15];
    tipLabel.layer.cornerRadius = 18.5;
    tipLabel.textAlignment = NSTextAlignmentCenter;
    tipLabel.layer.masksToBounds = YES;
    [self.view addSubview:tipLabel];
    
    CGSize size = [tipLabel.text sizeWithMaxSize:CGSizeMake(MAXFLOAT, MAXFLOAT) font:15];
    
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.navBarView.mas_bottom).offset(15);
        make.height.mas_equalTo(37);
        make.width.mas_equalTo(size.width+40);
    }];
    
    //分享成功
    if (isSuccess)
    {
        if ([self.delegate respondsToSelector:@selector(WPShareToCommonCaseSuccessWith:with:)])
        {
            [self.delegate WPShareToCommonCaseSuccessWith:self with:self.indexPath];
        }
    }
    
    [UIView animateWithDuration:2.0 animations:^{
        
        tipLabel.alpha = 0.0;
    } completion:^(BOOL finished) {
        
        [tipLabel removeFromSuperview];
        self.isShow = NO;
        
        //共享成功后返回
        if (isSuccess)
        {
            [self backBtnDidClick];
        }
    }];
}


/**
 共享到精华病例的结果提示
 */
-(void)showSharedSpecialRecordResult
{
    NSString *title = @"工作人员将在24小时内对您的病例进行审核,并且推送消息说明病例的审核结果";
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    NSMutableAttributedString *titleAtt = [[NSMutableAttributedString alloc] initWithString:title];
    [titleAtt addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:17.0] range:NSMakeRange(0, title.length)];
    [titleAtt addAttribute:NSForegroundColorAttributeName value:RGB_SAME(51) range:NSMakeRange(0, title.length)];
    [alertController setValue:titleAtt forKey:@"attributedTitle"];
    
    [alertController addAction:action];
    [self presentViewController:alertController animated:YES completion:nil];
}

-(UILabel *)tipLabel
{
    if (_tipLabel == nil)
    {
        _tipLabel = [UILabel new];
        _tipLabel.textColor = GlobalColor;
        _tipLabel.text = @"分享成功后将您的病例设定价格为 (2~10元)";
        _tipLabel.font = [UIFont systemFontOfSize:14];
        _tipLabel.hidden = !self.index;
        [self.view addSubview:_tipLabel];
        
        [_tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.top.equalTo(self.performCaseBtn.mas_bottom).offset(20*K_SCALE_ELSE_TABBAR);
        }];
    }
    return _tipLabel;
}


-(void)backBtnDidClick
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
